package com.cote.douhahou.pretloan.msg.widget;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentActivity;

import com.cote.douhahou.pretloan.beans.OtheAkomapalendrsInfo;
import com.cote.douhahou.pretloan.beans.ProcesAkomapalendsInfoData;
import com.cote.douhahou.pretloan.launcher.BaseContext;
import com.cote.douhahou.pretloan.network.HttpHelper;
import com.cote.douhahou.pretloan.utils.AkomapaLendConfigs;
import com.cote.douhahou.pretloan.utils.AkomapaLendUtil;
import com.cote.douhahou.pretloan.utils.image_akomapalend.ImageConvert;
import com.cote.douhahou.pretloan.R;
import com.cote.douhahou.pretloan.utils.PhotoAkomapalendSelectorDialog;

import java.io.File;
import java.util.TreeMap;

import pub.devrel.easypermissions.EasyPermissions;

public class OcrVieAkomapalendwManager extends BaseProcAkomapalendessWidgetManager {

    private FragmentActivity activ_akomapalendity;

    private View idCard_akomapalendView, passpor_akomapalendtView, drivingLi_akomapalendcenseView;
    private ImageView idCar_akomapalenddIv, passpo_akomapalendrtIv, driving_akomapalendLicenseIv;
    private TextView idCar_akomapalenddTv, passpo_akomapalendrtTv, drivingLi_akomapalendcenseTv;
    private TextView imgType_akomapalendTitleTv;
    private ImageButton img_akomapalend1Ib, img_akomapalend2Ib;
    private TextView img_akomapalend1Tv, img_akomapalend2Tv;
    private View img2_akomapalendView;

    private String image1Ur_akomapalendl_akomapalend, image2Ur_akomapalendl_akomapalend;
    private Bitmap image1Bit_akomapalendmap_akomapalend, image2Bitma_akomapalendp_akomapalend;

    private boolean isImageRe_akomapalendverse = false;

    private static final String CT_Id_akomapalendC ="National ID card", CT_Passp_akomapalendort ="Passport", CT_DrvingL_akomapalendicense ="Drving license";
    private static final String WD_IdC_akomapalendard ="IDCARD", WD_Passpo_akomapalendrt ="PASSPORT", WD_Drvin_akomapalendgLicense ="DRIVING";

    private String select_akomapalendType = CT_Id_akomapalendC;

    private Runnable startCame_akomapalendraRunnable;

    public String imgPa_akomapalendth = "";
    public Uri pho_akomapalendtoUri;

    public static final int Flag_StartCam_akomapalendera = 77;

    private ActivityResultLauncher<PickVisualMediaRequest> pickMe_akomapalenddia;

    private final Runnable processResp_akomapalendRunnable, imgUploadRe_akomapalendspRunnab_akomapalendle;


    public OcrVieAkomapalendwManager(View view, ProcesAkomapalendsInfoData data, String page, Runnable processRespRunnable, Runnable imgUploadRespRunnable){
        super(view,data,page);
        activ_akomapalendity = (FragmentActivity) mVi_akomapalendew.getContext();

        this.processResp_akomapalendRunnable = processRespRunnable;
        this.imgUploadRe_akomapalendspRunnab_akomapalendle = imgUploadRespRunnable;
    }

    @Override
    protected void in_akomapalendit(){

        idCard_akomapalendView = mVi_akomapalendew.findViewById(R.id.ipoa_view_idcard);
        passpor_akomapalendtView = mVi_akomapalendew.findViewById(R.id.ipoa_view_passport);
        drivingLi_akomapalendcenseView = mVi_akomapalendew.findViewById(R.id.ipoa_view_drivinglicense);
        idCar_akomapalenddIv = mVi_akomapalendew.findViewById(R.id.ipoa_iv_idcard);
        passpo_akomapalendrtIv = mVi_akomapalendew.findViewById(R.id.ipoa_iv_passport);
        driving_akomapalendLicenseIv = mVi_akomapalendew.findViewById(R.id.ipoa_iv_drivinglicense);
        idCar_akomapalenddTv = mVi_akomapalendew.findViewById(R.id.ipoa_tv_idcard);
        passpo_akomapalendrtTv = mVi_akomapalendew.findViewById(R.id.ipoa_tv_passport);
        drivingLi_akomapalendcenseTv = mVi_akomapalendew.findViewById(R.id.ipoa_tv_drivinglicense);
        imgType_akomapalendTitleTv = mVi_akomapalendew.findViewById(R.id.ipoa_tv_img_type_title);
        img_akomapalend1Ib = mVi_akomapalendew.findViewById(R.id.ipoa_ib_img1);
        img_akomapalend2Ib = mVi_akomapalendew.findViewById(R.id.ipoa_ib_img2);
        img_akomapalend1Tv = mVi_akomapalendew.findViewById(R.id.ipoa_tv_img1);
        img_akomapalend2Tv = mVi_akomapalendew.findViewById(R.id.ipoa_tv_img2);
        img2_akomapalendView = mVi_akomapalendew.findViewById(R.id.ipoa_view_img2);
        
        img_akomapalend1Ib.setOnClickListener(v -> {

            HttpHelper.inst().submitEvent(pa_akomapalendge,"IMAGE_1_CLICK","");

            new PhotoAkomapalendSelectorDialog(
                    mVi_akomapalendew.getContext(),
                    () -> {//打开相机
                        isImageRe_akomapalendverse = false;
                        star_akomapalendtCame_akomapalendra();
                    },
                    () -> {//相册选择
                        isImageRe_akomapalendverse = false;
                        ope_akomapalendnAl_akomapalendbum();
                    }
            ).show();

        });

        img_akomapalend2Ib.setOnClickListener(v -> {
            HttpHelper.inst().submitEvent(pa_akomapalendge,"IMAGE_2_CLICK","");

            new PhotoAkomapalendSelectorDialog(
                    mVi_akomapalendew.getContext(),
                    () -> {//打开相机
                        isImageRe_akomapalendverse = true;
                        star_akomapalendtCame_akomapalendra();
                    },
                    () -> {//相册选择
                        isImageRe_akomapalendverse = true;
                        ope_akomapalendnAl_akomapalendbum();
                    }
            ).show();

        });

        idCard_akomapalendView.setOnClickListener(v -> ini_akomapalendtTypeIdC_akomapalendard());
        passpor_akomapalendtView.setOnClickListener(v -> initT_akomapalendypePas_akomapalendsport());
        drivingLi_akomapalendcenseView.setOnClickListener(v -> initTypeD_akomapalendrvingLicense());

        ini_akomapalendtTypeIdC_akomapalendard();
        
    }

    public void nextC_akomapalendlick(String path){
        if (TextUtils.isEmpty(image1Ur_akomapalendl_akomapalend)||(TextUtils.isEmpty(image2Ur_akomapalendl_akomapalend)&&!select_akomapalendType.equalsIgnoreCase(CT_Passp_akomapalendort))){
            Toast.makeText(mVi_akomapalendew.getContext(), mVi_akomapalendew.getContext().getString(R.string.tips_upload_photo),Toast.LENGTH_SHORT).show();
            return;
        }

        HttpHelper.inst().processSubmit(
                activ_akomapalendity,
                path,
                new TreeMap<String,String>(){{
                    put("cardImgUrl", image1Ur_akomapalendl_akomapalend);
                    put("cardBackImgUrl", select_akomapalendType.equalsIgnoreCase(CT_Passp_akomapalendort) ? "": image2Ur_akomapalendl_akomapalend);
                    put("cardType", getTy_akomapalendpeWd());
                }},
                () -> HttpHelper.inst().process(activ_akomapalendity,() -> {if (processResp_akomapalendRunnable !=null) processResp_akomapalendRunnable.run();}
        ));
    }

    @Override
    public boolean checkI_akomapalendnput() {
        return false;
    }

    @Override
    public String getInp_akomapalendut() {
        return "";
    }


    private void star_akomapalendtCame_akomapalendra() {

        HttpHelper.inst().submitEvent(pa_akomapalendge,"START_CAMERA_CLICK","");

        //拍照流程
        startCame_akomapalendraRunnable = () -> {
            Intent intent = new Intent();
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

            String imageFilePath = this.getIma_akomapalendgeFilePa_akomapalendth();
            File imageFile = new File(imageFilePath);
            imgPa_akomapalendth = imageFilePath;
            String providerAuthority = BaseContext.instance().getPackageName() + ".file_provider";
            pho_akomapalendtoUri = FileProvider.getUriForFile(BaseContext.instance(), providerAuthority, imageFile);

            intent.putExtra(MediaStore.EXTRA_OUTPUT, pho_akomapalendtoUri);
            if (activ_akomapalendity !=null) activ_akomapalendity.startActivityForResult(intent, Flag_StartCam_akomapalendera);
        };
        //申请Permission
        if (!AkomapaLendUtil.permissionsHasAgree(mVi_akomapalendew.getContext(), Manifest.permission.CAMERA)) {
            if (activ_akomapalendity !=null)
                EasyPermissions.requestPermissions(activ_akomapalendity,
                        activ_akomapalendity.getString(R.string.request_permission_camera),
                        AkomapaLendConfigs.PermissionCCamera, Manifest.permission.CAMERA);
        } else startCame_akomapalendraRunnable.run();
    }

    private void ope_akomapalendnAl_akomapalendbum() {

        HttpHelper.inst().submitEvent(pa_akomapalendge,"OPEN_ALBUM_CLICK","");

        if (pickMe_akomapalenddia !=null)
            pickMe_akomapalenddia.launch(
                    new PickVisualMediaRequest.Builder()
                            .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
                            .build()
            );
    }

    public void set_akomapalendPick_akomapalendMe(ActivityResultLauncher<PickVisualMediaRequest> pickMe_akomapalenddia) {
        this.pickMe_akomapalenddia = pickMe_akomapalenddia;
    }

    public void onPh_akomapalendot_akomapalendoGet() {
        if (pho_akomapalendtoUri == null) {
            if (isImageRe_akomapalendverse) image2Ur_akomapalendl_akomapalend = null;
            else image1Ur_akomapalendl_akomapalend = null;
            Toast.makeText(mVi_akomapalendew.getContext(), mVi_akomapalendew.getContext().getString(R.string.tips_upload_photo_again),Toast.LENGTH_SHORT).show();
            return;
        }

        if (!TextUtils.isEmpty(imgPa_akomapalendth)) {
            ImageConvert.startConvertImage(
                    new File(imgPa_akomapalendth),
                    (localPath, thumpImg) -> {
                        if (isImageRe_akomapalendverse) image2Bitma_akomapalendp_akomapalend = thumpImg;
                        else image1Bit_akomapalendmap_akomapalend = thumpImg;
                        new Thread(() -> HttpHelper.inst().saveImage(activ_akomapalendity,localPath,() -> {
                            if (imgUploadRe_akomapalendspRunnab_akomapalendle !=null) imgUploadRe_akomapalendspRunnab_akomapalendle.run();
                        })).start();
                    }
            );
        } else {
            if (isImageRe_akomapalendverse) image2Ur_akomapalendl_akomapalend = null;
            else image1Ur_akomapalendl_akomapalend = null;
            Toast.makeText(mVi_akomapalendew.getContext(), mVi_akomapalendew.getContext().getString(R.string.tips_upload_photo_again),Toast.LENGTH_SHORT).show();
        }
    }

    public void onPhot_akomapalendoUploadRe_akomapalendsponse() {

        String imagePath = OtheAkomapalendrsInfo.instance().getImgPath_akomapalend();

        if (TextUtils.isEmpty(imagePath)||(!isImageRe_akomapalendverse && image1Bit_akomapalendmap_akomapalend ==null)||(isImageRe_akomapalendverse && image2Bitma_akomapalendp_akomapalend ==null)){
            Toast.makeText(mVi_akomapalendew.getContext(), mVi_akomapalendew.getContext().getString(R.string.tips_upload_photo_again),Toast.LENGTH_SHORT).show();
            return;
        }

        if (isImageRe_akomapalendverse){
            this.image2Ur_akomapalendl_akomapalend = imagePath;
            img_akomapalend2Ib.setImageBitmap(image2Bitma_akomapalendp_akomapalend);
        }else {
            this.image1Ur_akomapalendl_akomapalend = imagePath;
            img_akomapalend1Ib.setImageBitmap(image1Bit_akomapalendmap_akomapalend);
        }

    }

    @SuppressLint("SetTextI18n")
    private void ini_akomapalendtTypeIdC_akomapalendard(){

        HttpHelper.inst().submitEvent(pa_akomapalendge,"TYPE_ID_CARD_CLICK","");

        idCard_akomapalendView.setBackgroundResource(R.drawable.back_border_purple_2);
        idCar_akomapalenddIv.setBackgroundResource(R.drawable.image_personal);
        idCar_akomapalenddTv.setTextColor(mVi_akomapalendew.getContext().getColor(R.color.word_light));

        passpor_akomapalendtView.setBackgroundResource(R.drawable.back_gray_round_corner);
        passpo_akomapalendrtIv.setBackgroundResource(R.drawable.image_earth);
        passpo_akomapalendrtTv.setTextColor(mVi_akomapalendew.getContext().getColor(R.color.word_gray));

        drivingLi_akomapalendcenseView.setBackgroundResource(R.drawable.back_gray_round_corner);
        driving_akomapalendLicenseIv.setBackgroundResource(R.drawable.image_car_2);
        drivingLi_akomapalendcenseTv.setTextColor(mVi_akomapalendew.getContext().getColor(R.color.word_gray));

        imgType_akomapalendTitleTv.setText(mVi_akomapalendew.getContext().getString(R.string.ocr_type_id_card));

        clearI_akomapalendmg();

        select_akomapalendType = CT_Id_akomapalendC;
        img_akomapalend1Tv.setText(mVi_akomapalendew.getContext().getString(R.string.ocr_idcard_desc_front));
        img_akomapalend2Tv.setText(mVi_akomapalendew.getContext().getString(R.string.ocr_idcard_desc_back));
        img2_akomapalendView.setVisibility(View.VISIBLE);
    }

    @SuppressLint("SetTextI18n")
    private void initT_akomapalendypePas_akomapalendsport(){

        HttpHelper.inst().submitEvent(pa_akomapalendge,"TYPE_PASSPORT_CLICK","");

        idCard_akomapalendView.setBackgroundResource(R.drawable.back_gray_round_corner);
        idCar_akomapalenddIv.setBackgroundResource(R.drawable.image_personal_gray);
        idCar_akomapalenddTv.setTextColor(mVi_akomapalendew.getContext().getColor(R.color.word_gray));

        passpor_akomapalendtView.setBackgroundResource(R.drawable.back_border_purple_2);
        passpo_akomapalendrtIv.setBackgroundResource(R.drawable.image_work);
        passpo_akomapalendrtTv.setTextColor(mVi_akomapalendew.getContext().getColor(R.color.word_light));

        drivingLi_akomapalendcenseView.setBackgroundResource(R.drawable.back_gray_round_corner);
        driving_akomapalendLicenseIv.setBackgroundResource(R.drawable.image_car_2);
        drivingLi_akomapalendcenseTv.setTextColor(mVi_akomapalendew.getContext().getColor(R.color.word_gray));

        imgType_akomapalendTitleTv.setText(mVi_akomapalendew.getContext().getString(R.string.ocr_type_passport));

        clearI_akomapalendmg();

        select_akomapalendType = CT_Passp_akomapalendort;
        img_akomapalend1Tv.setText(mVi_akomapalendew.getContext().getString(R.string.ocr_passport_desc));
        img2_akomapalendView.setVisibility(View.GONE);

    }

    @SuppressLint("SetTextI18n")
    private void initTypeD_akomapalendrvingLicense(){

        HttpHelper.inst().submitEvent(pa_akomapalendge,"TYPE_DRIVING_LICENSE_CLICK","");

        idCard_akomapalendView.setBackgroundResource(R.drawable.back_gray_round_corner);
        idCar_akomapalenddIv.setBackgroundResource(R.drawable.image_personal_gray);
        idCar_akomapalenddTv.setTextColor(mVi_akomapalendew.getContext().getColor(R.color.word_gray));

        passpor_akomapalendtView.setBackgroundResource(R.drawable.back_gray_round_corner);
        passpo_akomapalendrtIv.setBackgroundResource(R.drawable.image_earth);
        passpo_akomapalendrtTv.setTextColor(mVi_akomapalendew.getContext().getColor(R.color.word_gray));

        drivingLi_akomapalendcenseView.setBackgroundResource(R.drawable.back_border_purple_2);
        driving_akomapalendLicenseIv.setBackgroundResource(R.drawable.image_car);
        drivingLi_akomapalendcenseTv.setTextColor(mVi_akomapalendew.getContext().getColor(R.color.word_light));

        imgType_akomapalendTitleTv.setText(mVi_akomapalendew.getContext().getString(R.string.ocr_type_driving_license));

        clearI_akomapalendmg();

        select_akomapalendType = CT_DrvingL_akomapalendicense;
        img_akomapalend1Tv.setText(mVi_akomapalendew.getContext().getString(R.string.ocr_drivinglicense_desc_front));
        img_akomapalend2Tv.setText(mVi_akomapalendew.getContext().getString(R.string.ocr_drivinglicense_desc_back));
        img2_akomapalendView.setVisibility(View.VISIBLE);

    }

    private void clearI_akomapalendmg(){
        image1Ur_akomapalendl_akomapalend = "";
        image2Ur_akomapalendl_akomapalend = "";
        image1Bit_akomapalendmap_akomapalend = null;
        image2Bitma_akomapalendp_akomapalend = null;

        img_akomapalend1Ib.setImageResource(R.drawable.image_face_3);
        img_akomapalend2Ib.setImageResource(R.drawable.image_face_2);
    }

    private String getTy_akomapalendpeWd(){
        switch (select_akomapalendType){
            case CT_Id_akomapalendC:
                return WD_IdC_akomapalendard;
            case CT_Passp_akomapalendort:
                return WD_Passpo_akomapalendrt;
            case CT_DrvingL_akomapalendicense:
                return WD_Drvin_akomapalendgLicense;
        }
        return "";
    }

    public void onCam_akomapalenderaPermissio_akomapalendnAgree(){
        if (startCame_akomapalendraRunnable !=null) startCame_akomapalendraRunnable.run();
    }

    /**
     * 获取图片路径
     */
    private String getIma_akomapalendgeFilePa_akomapalendth() {
        String pictureId = System.currentTimeMillis() + "";
        String imgDir = getSa_akomapalendndboxFolde_akomapalendrPath();
        return (imgDir + File.separator + pictureId + ".jpg");
    }

    /**
     * 获取沙盒路径
     */
    private String getSa_akomapalendndboxFolde_akomapalendrPath() {
        String inAppFolder = BaseContext.instance().getFilesDir().getAbsolutePath();
        inAppFolder += File.separator;
        inAppFolder += AkomapaLendConfigs.MyProduct;
        inAppFolder += "_PICS";

        File folderFile = new File(inAppFolder);
        if (!folderFile.exists()) {
            folderFile.mkdirs();
        }

        return inAppFolder;
    }

}
